// AI侦探应用数据服务层

import { CaseRepository, SuspectRepository, ClueRepository, RepositoryFactory } from './DATA_ACCESS';

// 数据服务类 - 提供对所有仓库的访问
export class DataService {
  private static instance: DataService;
  
  // 仓库实例
  private caseRepository: CaseRepository;
  private suspectRepository: SuspectRepository;
  private clueRepository: ClueRepository;

  // 私有构造函数
  private constructor() {
    this.caseRepository = RepositoryFactory.createCaseRepository();
    this.suspectRepository = RepositoryFactory.createSuspectRepository();
    this.clueRepository = RepositoryFactory.createClueRepository();
  }

  // 单例模式获取实例
  static getInstance(): DataService {
    if (!DataService.instance) {
      DataService.instance = new DataService();
    }
    return DataService.instance;
  }

  // ========== 案件相关服务 ==========

  // 获取所有案件
  async getAllCases(): Promise<any[]> {
    try {
      return await this.caseRepository.getAllItems();
    } catch (error) {
      console.error('Failed to get all cases:', error);
      return [];
    }
  }

  // 根据ID获取案件
  async getCaseById(id: string): Promise<any | null> {
    try {
      return await this.caseRepository.getItemById(id);
    } catch (error) {
      console.error(`Failed to get case by id ${id}:`, error);
      return null;
    }
  }

  // 添加新案件
  async addCase(caseData: any): Promise<boolean> {
    try {
      return await this.caseRepository.addItem(caseData);
    } catch (error) {
      console.error('Failed to add case:', error);
      return false;
    }
  }

  // 更新案件
  async updateCase(id: string, caseData: any): Promise<boolean> {
    try {
      return await this.caseRepository.updateItem(id, caseData);
    } catch (error) {
      console.error(`Failed to update case ${id}:`, error);
      return false;
    }
  }

  // 删除案件
  async deleteCase(id: string): Promise<boolean> {
    try {
      return await this.caseRepository.deleteItem(id);
    } catch (error) {
      console.error(`Failed to delete case ${id}:`, error);
      return false;
    }
  }

  // 获取指定状态的案件
  async getCasesByStatus(status: string): Promise<any[]> {
    try {
      return await this.caseRepository.getCasesByStatus(status);
    } catch (error) {
      console.error(`Failed to get cases by status ${status}:`, error);
      return [];
    }
  }

  // ========== 嫌疑人相关服务 ==========

  // 获取所有嫌疑人
  async getAllSuspects(): Promise<any[]> {
    try {
      return await this.suspectRepository.getAllItems();
    } catch (error) {
      console.error('Failed to get all suspects:', error);
      return [];
    }
  }

  // 根据ID获取嫌疑人
  async getSuspectById(id: string): Promise<any | null> {
    try {
      return await this.suspectRepository.getItemById(id);
    } catch (error) {
      console.error(`Failed to get suspect by id ${id}:`, error);
      return null;
    }
  }

  // 获取指定案件的嫌疑人
  async getSuspectsByCase(caseId: string): Promise<any[]> {
    try {
      return await this.suspectRepository.getSuspectsByCase(caseId);
    } catch (error) {
      console.error(`Failed to get suspects by case ${caseId}:`, error);
      return [];
    }
  }

  // 添加新嫌疑人
  async addSuspect(suspectData: any): Promise<boolean> {
    try {
      return await this.suspectRepository.addItem(suspectData);
    } catch (error) {
      console.error('Failed to add suspect:', error);
      return false;
    }
  }

  // ========== 线索相关服务 ==========

  // 获取所有线索
  async getAllClues(): Promise<any[]> {
    try {
      return await this.clueRepository.getAllItems();
    } catch (error) {
      console.error('Failed to get all clues:', error);
      return [];
    }
  }

  // 根据ID获取线索
  async getClueById(id: string): Promise<any | null> {
    try {
      return await this.clueRepository.getItemById(id);
    } catch (error) {
      console.error(`Failed to get clue by id ${id}:`, error);
      return null;
    }
  }

  // 获取指定案件的线索
  async getCluesByCase(caseId: string): Promise<any[]> {
    try {
      return await this.clueRepository.getCluesByCase(caseId);
    } catch (error) {
      console.error(`Failed to get clues by case ${caseId}:`, error);
      return [];
    }
  }

  // 获取关键线索
  async getKeyClues(): Promise<any[]> {
    try {
      return await this.clueRepository.getKeyClues();
    } catch (error) {
      console.error('Failed to get key clues:', error);
      return [];
    }
  }

  // ========== 组合数据服务 ==========

  // 获取案件详情（包含关联的嫌疑人和线索）
  async getCaseDetail(caseId: string): Promise<any | null> {
    try {
      const caseData = await this.getCaseById(caseId);
      if (!caseData) return null;

      const suspects = await this.getSuspectsByCase(caseId);
      const clues = await this.getCluesByCase(caseId);

      return {
        ...caseData,
        suspects,
        clues
      };
    } catch (error) {
      console.error(`Failed to get case detail for ${caseId}:`, error);
      return null;
    }
  }

  // 获取正在调查的案件数量
  async getActiveCaseCount(): Promise<number> {
    try {
      const activeCases = await this.getCasesByStatus('INVESTIGATING');
      return activeCases.length;
    } catch (error) {
      console.error('Failed to get active case count:', error);
      return 0;
    }
  }

  // ========== 数据初始化服务 ==========

  // 初始化数据（在应用启动时调用）
  async initializeData(): Promise<void> {
    try {
      // 这里可以添加数据初始化逻辑
      // 例如检查数据是否存在，不存在则创建默认数据
      console.log('Data service initialized successfully');
    } catch (error) {
      console.error('Failed to initialize data service:', error);
    }
  }
}

// ========== 使用示例 ==========
/*
// 在组件中使用数据服务

// 1. 导入数据服务
import { DataService } from '../services/DATA_SERVICE';

// 2. 获取数据服务实例
const dataService = DataService.getInstance();

// 3. 使用服务方法
async function loadCases() {
  const cases = await dataService.getAllCases();
  console.log('Loaded cases:', cases);
}

// 4. 加载特定案件的详情
async function loadCaseDetail(caseId: string) {
  const caseDetail = await dataService.getCaseDetail(caseId);
  if (caseDetail) {
    console.log('Case detail:', caseDetail);
    console.log('Associated suspects:', caseDetail.suspects);
    console.log('Associated clues:', caseDetail.clues);
  }
}
*/